package slxy.jiangtao.dts.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.core.common.bean.JSONResult;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.core.util.MyClassLoader;
import slxy.jiangtao.dts.entity.sys.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Code must be sexy
 * Created by Jiang Tao on 2017/4/16.
 * 说明：数据字典controller(包括DictionariesNews，Major,College,Systemconfig)
 * 注意：添加一个数据字典类，要修改dataUpdate方法的witch
 */
@Controller
@RequestMapping("dictionaries")
public class DictionariesController {
    private static final Logger logger = LoggerFactory.getLogger(DictionariesController.class);

    @Autowired
    private CommonService commonService;

    /**
     * 对于本类的私有根据类名获得Class方法
     *
     * @param classname 实体类名
     * @return 泛型实体类Class
     */
    private Class getClass(String classname) {
        return MyClassLoader.getClassByScn(Constants.BASE_ENTITY_PACKAGE_SYS + classname);
    }

    /**
     * 数据字典通用Index页面跳转
     *
     * @param classname 实体类名
     * @param modelMap
     * @return 页面路径
     */
    @RequestMapping("page/{classname}")
    public String forwordPge(@PathVariable String classname, ModelMap modelMap) {
        modelMap.put("dataList", JSON.toJSONString(commonService.getList(getClass(classname))));
        if (classname.trim().equals("Major")) {
            List<Map<Integer, String>> collegeMap = new ArrayList<>();
            List<College> colleges = commonService.getList(College.class);
            Optional.ofNullable(colleges).ifPresent(
                    collegeList ->
                            collegeList.forEach(
                                    college -> {
                                        Map<Integer, String> map = new HashedMap();
                                        map.put(college.getId(), college.getName());
                                        collegeMap.add(map);
                                    }
                            )
            );
            modelMap.put("collegeList", JSON.toJSONString(collegeMap));
        }
        return "dictionaries/" + classname.toLowerCase();
    }

    /**
     * 数据字典通用数据列表获取
     *
     * @param classname 实体类名
     * @return json格式字符结果集
     */
    @RequestMapping("data/{classname}")
    @ResponseBody
    public String getData(@PathVariable String classname) {
        return JSON.toJSONString(commonService.getList(getClass(classname)));
    }

    /**
     * 数据字典通用删除方法
     *
     * @param id 实体主键id
     */
    @RequestMapping("delete/{classname}")
    @ResponseBody
    public JSONResult delete(@PathVariable String classname, @RequestParam Integer id) {
        try {
            commonService.deleteEntityById(getClass(classname), id);
        } catch (Exception e) {
            logger.error(classname + "类实例删除失败  ", e);
            return JSONResult.failure("删除失败");
        }
        return JSONResult.success();
    }

    /**
     * 数据字典通用保存or更新方法
     */
    @RequestMapping(value = "update/{classname}", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult dataUpdate(HttpServletRequest request, @PathVariable String classname) {
        try {
            String hs = request.getParameter("json");
            String str = URLDecoder.decode(hs, "UTF-8").substring(1).replaceAll("]", "");
            Optional.ofNullable(classname).ifPresent(
                    val -> {
                        switch (val.trim()) {
                            case "DictionariesNews":
                                DictionariesNews dictionariesNews = JSONObject.parseObject(str, DictionariesNews.class);
                                commonService.saveOrUpdate(dictionariesNews);
                                break;
                            case "Major":
                                Major major = JSONObject.parseObject(str, Major.class);
                                commonService.saveOrUpdate(major);
                                break;
                            case "College":
                                College college = JSONObject.parseObject(str, College.class);
                                commonService.saveOrUpdate(college);
                                break;
                            case "DictionariesTask":
                                DictionariesTask dictionariesTask = JSONObject.parseObject(str, DictionariesTask.class);
                                commonService.saveOrUpdate(dictionariesTask);
                                break;
                            case "Systemconfig":
                                Systemconfig systemconfig = JSONObject.parseObject(str, Systemconfig.class);
                                commonService.saveOrUpdate(systemconfig);
                                break;
                            default:
                                logger.warn("类名参数为空");
                        }
                    }
            );
        } catch (Exception e) {
            logger.error("保存失败", e);
            return JSONResult.failure("保存失败");
        }
        return JSONResult.success();
    }
}
